//
//  CNMainViewController.m
//  chuiniu
//
//  Created by zheng ji on 14-9-20.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "CNMainViewController.h"
#import "CNViewController.h"
#import "CNPlayer.h"
#import "CNAppDelegate.h"
#import "CNGameUtil.h"
#import "CommonConfigUtil.h"
#import "CNOnlinePlayerController.h"
@interface CNMainViewController ()
{
    //CNGameClient* gameClient;
    CNAppDelegate* appDelegate;
    NSUserDefaults* _userDefaults;
    iToast* toast;
     CNPlayer* tempVSPlayer;
}
@end

@implementation CNMainViewController
- (IBAction)gameSetButtonClick:(UIButton *)sender {
    
    
    UINavigationController* navi=(UINavigationController*)[ self.storyboard instantiateViewControllerWithIdentifier:@"GameSetNaviController"];
    
    [self presentViewController:navi animated:YES completion:nil];
    
    
}

- (IBAction)mutilButtonClick:(UIButton *)sender {
    
   CNPlayer* player= [CNGameUtil getCurrentPlayerFromUserDefaults];
    if(player!=nil){
        int coin=player.coins.intValue;
        if(coin<=0){
            [self showToast:-1 title:[NSString stringWithFormat:@"您的金币数为%@,不能邀请对战!",player.coins ] duration:kToastDuration2Second position:kToastPositionCenter countDown:NO];
            return ;
        }
    }
    if (!appDelegate.gameClient.isConnected) {
    
        [self showToast:-1 title:@"未连接到网络,请稍后再试" duration:kToastDuration5Second position:kToastPositionCenter countDown:YES];
         [appDelegate.gameClient connectToServer];
    }else{
    
     //  UINavigationController* navi=(UINavigationController*)[ self.storyboard instantiateViewControllerWithIdentifier:@"CNOnlinePlayerNaviController"];
    
         CNOnlinePlayerController* onlineCtrl=(CNOnlinePlayerController*)[ self.storyboard instantiateViewControllerWithIdentifier:@"CNOnlinePlayerController"];
        
        [self.navigationController pushViewController:onlineCtrl animated:YES];
       //[self presentViewController:navi animated:YES completion:nil];
    }
  
}
- (IBAction)singleButtonClick:(UIButton *)sender {
    
    /*
    if (!appDelegate.gameClient.isConnected) {
        
        [self showToast:-1 title:@"未连接到网络,将无法计算金币" duration:kToastDuration3Second position:kToastPositionCenter countDown:NO];
        
       
     
    }*/
    
   CNViewController* viewCtrl=(CNViewController*)[ self.storyboard instantiateViewControllerWithIdentifier:@"CNViewController"];
    appDelegate.gamePlayModel=GameModelSinglePlayer;
     viewCtrl.gameModel=GameModelSinglePlayer;
    viewCtrl.gameStatus=GameStatusNormal;
    //viewCtrl.gameClient=gameClient;
    CNPlayer* vsPlayer=[[CNPlayer alloc]init];
    vsPlayer.playerName=@"手机";
    appDelegate.vsPlayer=vsPlayer;
    appDelegate.gameClient.gameMainViewController=viewCtrl;
    [self presentViewController:viewCtrl animated:YES completion:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
 
   // UIColor* bgColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
   // self.view.backgroundColor=bgColor;
    _userDefaults=[NSUserDefaults standardUserDefaults];
    
    appDelegate=(CNAppDelegate*)[UIApplication sharedApplication].delegate;
    
    appDelegate.player=[CNGameUtil getCurrentPlayerFromUserDefaults];
    
    /*
    if(appDelegate.gameClient ==nil){
       appDelegate.gameClient=[[CNGameClient alloc]init];
      [appDelegate.gameClient connectToServer];
    }*/
    
    appDelegate.scence=ScenceMainView;
    appDelegate.gameClient.gameMainViewController=self;

    
       [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkVersionTimer:) userInfo:nil repeats:NO];

}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
    
    
    [self checkPlayerName];
    
  
    
   
}

/**
 检查是否已经有玩家名称，否则提示用户输入
 */
-(void)checkPlayerName{
    CNPlayer* player=  [CNGameUtil getCurrentPlayerFromUserDefaults];
    
    if(player ==nil || player.playerName==nil || [player.playerName isEqualToString:@""]){
        
        UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:@"您还没有昵称哦,快来取一个吧!" delegate: self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
        alertView.tag=tagAlertViewRegisterPlayer;
        [alertView show];
        alertView=nil;
        
    }else{
        appDelegate.player=player;
        [appDelegate.gameClient sendLoginCommand:player];
    }
    
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    if([alertView tag]==tagAlertViewUpgrade && buttonIndex == 0) {
        
        NSString *appUrl=  [_userDefaults objectForKey:@"appUrl"];
        if(nil!=appUrl && ![@"" isEqualToString:appUrl]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrl]];
        }
        
    }else if(alertView.tag==tagAlertViewRegisterPlayer){
        //输入玩家名称
        UITextField* tf=  [alertView textFieldAtIndex:0];
        if([tf.text isEqualToString:@""]){
            [self checkPlayerName];
        }else{
            
                [appDelegate.gameClient registerPlayer:tf.text];
            
        }
    }else if([alertView tag]==tagAlertViewRequestPK){
        if(  buttonIndex == 0) {
            
            //接受请求对战
            [self startMutilPlay];
        }else{
            //拒绝对战请求
            [appDelegate.gameClient sendRejectVSCommand:tempVSPlayer];
        }
    }
}
 

/**
 有玩家邀请对战
 */
-(void) requestPK:(CNPlayer*)vsPlayer{
    
    tempVSPlayer=vsPlayer;
    UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"玩家[%@]想和您对战，是否接受?",vsPlayer.playerName] delegate: self cancelButtonTitle:@"接受" otherButtonTitles:@"残忍拒绝", nil];
    // alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
    alertView.tag=tagAlertViewRequestPK;
    [alertView show];
    alertView=nil;
    
    
}

//开启对战游戏
-(void)startMutilPlay{
    CNAppDelegate* appD=(CNAppDelegate*)[UIApplication sharedApplication].delegate;
    
    //发送接收对战消息
    [appD.gameClient sendAcceptVSCommand:appD.player vsPlayerID:tempVSPlayer];
    
    CNViewController* viewCtrl=(CNViewController*)[ self.storyboard instantiateViewControllerWithIdentifier:@"CNViewController"];
    
    viewCtrl.gameModel=GameModelMutilPlayer;
    //viewCtrl.gameStatus=GameStatusNormal;
    appD.vsPlayer=tempVSPlayer;
    appD.gamePlayModel=GameModelMutilPlayer;
    appD.gameClient.gameMainViewController=viewCtrl;
    appD.gameStatus=GameStatusPlaying;
    [self presentViewController:viewCtrl animated:YES completion:nil];
}


-(void)hiddenToastView{
    if(toast !=nil){
        [toast hideToast:nil];
        toast=nil;
    }
    
}
-(void)showToast:(int)tag title:(NSString*)title duration:(ToastDuration)duration position:(ToastPosition)position{
    [self showToast:tag title:title duration:duration position:position countDown:YES];
}
-(void)showToast:(int)tag title:(NSString*)title duration:(ToastDuration)duration position:(ToastPosition)position countDown:(BOOL)countDown{
    
    [self hiddenToastView];
    toast = [iToast makeToast:title];
    toast.tag=tag;
    toast.toastDelegate=self;
    toast.countDown=countDown;
    [toast setToastPosition:position];
    [toast setToastDuration:duration];
    [toast show];
}
-(void)toastTimeOver:(int)toastTag{
    
}


-(void) checkVersionTimer:(NSTimer*)theTimer{
    [self checkVersion];
    [theTimer invalidate];
}



-(void)checkVersion{
    
    if([CommonConfigUtil checkVersion]){
        
        NSString *versionNumber=[_userDefaults objectForKey:@"versionNumber"];
        NSString *appUrl=[_userDefaults objectForKey:@"appUrl"];
        // NSString *appCommentUrl=[_userDefaults objectForKey:@"appCommentUrl"];
        NSString *description=[_userDefaults objectForKey:@"description"];
        
        if(nil==appUrl)appUrl=@"";
        if(nil==versionNumber)versionNumber=@"";
        if(nil==description)description=@"";
        //versionNumber=@"3.0";
        
        if(![@"" isEqualToString:appUrl] && nil!=versionNumber&& ![@"" isEqualToString:versionNumber]&& [versionNumber compare: [CommonConfigUtil getCurrVersion] ]==NSOrderedDescending ){
            
            
            NSString *strMessge;
            if(nil!=description&&![@"" isEqualToString:description]){
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！%@",versionNumber,description];
            }else{
                strMessge=[NSString stringWithFormat:@"%@版本发布啦！是否需要升级？",versionNumber];
            }
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本升级" message:strMessge                                                           delegate:self  cancelButtonTitle:@"立即升级" otherButtonTitles: @"忽略",nil];
            [alert setTag:tagAlertViewUpgrade];
            
            [alert show];
            
            alert=nil;
        }
        
    }
    
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
   
   // NSLog(@"");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
